package com.mazaiting.classpath;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;

/**
 * 解析尾部是*号的路径
 * 通配符类路径不能递归匹配子目录下的JAR文件
 * @author mazaiting
 * @since 2021/8/10
 */
public class WildcardEntry implements Entry {
    /**
     * 组合读取类列表
     */
    private final LinkedList<Entry> wildcardEntryList = new LinkedList<>();

    public WildcardEntry(String path) {
        String newPath = path.substring(0, path.length() - 1);
        File[] files = FileUtil.file(newPath).listFiles();
        if (ObjectUtil.isNotNull(files)) {
            Arrays.stream(files).forEach(file -> {
                String tmpPath = file.getPath();
                if (tmpPath.endsWith(".jar") || tmpPath.endsWith(".JAR")) {
                    Entry entry = EntryFactory.newEntry(tmpPath);
                    wildcardEntryList.add(entry);
                }
            });
        }
    }

    @Override
    public ClassResponse readClass(String className) {
        for (Entry entry : this.wildcardEntryList) {
            ClassResponse classResponse = entry.readClass(className);
            if (ObjectUtil.isEmpty(classResponse.getError())) {
                return classResponse;
            }
        }
        ClassResponse classResponse = new ClassResponse();
        classResponse.setError("class not found: " + className);
        return classResponse;
    }

    @Override
    public String toString() {
        return StringUtils.join(
                this.wildcardEntryList
                        .stream()
                        .map(Entry::toString)
                        .toArray(), File.pathSeparator);
    }
}


















